package me.spring.cloud.common.components.oauth2.exception;

import me.spring.cloud.common.components.oauth2.userdetails.exception.AuthServiceException;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

/**
 * 异常转换器 登录发生异常时指定
 *
 * @author diyangfeng
 */
@Slf4j
public class CustomerWebResponseExceptionTranslator implements WebResponseExceptionTranslator {

  @Override
  public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
    if (e instanceof AuthServiceException) {
      return ResponseEntity.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
          .body(new CustomOauthException(e.getMessage()));
    }
    if (e instanceof InvalidGrantException) {
      return ResponseEntity.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
          .body(new CustomOauthException("用户名或密码错误"));
    }
    if (e instanceof InternalAuthenticationServiceException) {
      //TODO 待统一异常返回信息
      return ResponseEntity.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
          .body(new CustomOauthException(e.getMessage()));
    }
    OAuth2Exception oAuth2Exception = (OAuth2Exception) e;
    return ResponseEntity.status(oAuth2Exception.getHttpErrorCode())
        .body(new CustomOauthException(oAuth2Exception.getMessage()));
  }
}
